package shaka.ui.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;

public class MkLinkUtils {
	public static boolean mkLink(File targetPath, File linkedPath) throws IOException {
		try {
			if (!linkedPath.exists() && !targetPath.exists()) throw new RuntimeException(
					"Can't execute both path exist !!");
			if (!linkedPath.exists()) {
				FileUtils.copyDirectory(targetPath, linkedPath);
			}
			if (targetPath.exists()) {
				FileUtils.deleteDirectory(targetPath);
			}
			String[] cmd;
			if (SystemUtils.IS_OS_WINDOWS) {
				cmd = new String[] { "cmd.exe", "/C", "mklink", "/j", wapperStr(targetPath), wapperStr(linkedPath) };
			} else if (SystemUtils.IS_OS_LINUX) {
				cmd = new String[] { "ln", "-s", wapperStr(targetPath), wapperStr(linkedPath) };
			} else {
				throw new RuntimeException("Unsupport system ...");
			}
			Process p = Runtime.getRuntime().exec(cmd);
			int exitcode = p.waitFor();
			return exitcode == 0;
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	private static String wapperStr(File f) {
		return "\"" + f.getAbsolutePath() + "\"";
	}
}
